#!/bin/sh

op=$1

echo_help()
{
  echo "Usage:$0 {start|stop|session <ipAddr> <target>}"
}

check_ip()
{
  a=$1
  result=`ping -w 1 -c 1 $a 2> /dev/null`
  if [ "$?" != 0 ] ;then
    echo "can't connect to ip ${a}"
    exit 1
  fi
}

validate_ip()
{
  a=$1

  ip=`echo "${a}" | awk -F':' '{print $1}'`
  if [ -z "$ip" ]; then
      echo_help
      exit 1
  fi

  check_ip "${ip}"
}

validate_target()
{
  a=$1

  if [ -z "$a" ]; then
    echo_help
    exit 1
  fi
}

starts()
{
  ipAddr=$1
  target=$2

  iqn="$ipAddr 3260 $target"

  echo `lsdev -Cc disk | grep "iSCSI" | awk -F' ' '{print $1}'` > /tmp/hdisktemp
  result=`cat /etc/iscsi/targets | grep "$iqn"`
  if [ -z "$result" ];then
      echo "$iqn" >> /etc/iscsi/targets
      cfgmgr -l iscsi0 > /dev/null 2> /dev/null
  fi
  hdisks=`lsdev -Cc disk | grep "iSCSI" | awk -F' ' '{print $1}'`
  for hdisk in ${hdisks} ; do
      exists=`grep "$hdisk" /tmp/hdisktemp`
      if [ -z "$exists" ]; then
        echo "---:${hdisk}"
        rm -fr /tmp/hdisktemp
        exit 0
      fi
  done
  echo "FAILED: {start iscsi}"
  rm -fr /tmp/hdisktemp
  exit 1
}

stops()
{
  ipAddr=$1
  target=$2

  iqn="$ipAddr 3260 $target"
  result=`cat /etc/iscsi/targets | grep -v "$iqn"`
  if [ -n "$result" ];then
    echo "$result" > /etc/iscsi/targets
    cfgmgr -l iscsi0 > /dev/null 2> /dev/null
  fi
  echo "OK"
}

sessions()
{
  cat /etc/iscsi/targets | grep -v "^#" | grep "iqn"
}

case $op in
start)
  ipAddr=$2
  target=$3

  validate_ip ${ipAddr}
  validate_target ${target}

  starts ${ipAddr} ${target}
  ;;

stop)
  ipAddr=$2
  target=$3

  validate_ip ${ipAddr}
  validate_target ${target}

  stops ${ipAddr} ${target}

  ;;
session)
  sessions
  ;;
*)
  echo_help
  exit 1
esac